package mn.asri.teaproc.server;

import mn.asri.teaproc.client.BaseModel;
import mn.asri.teaproc.client.Crypto;
import mn.asri.teaproc.client.PocPayload;

/**
 * @author $Author: mikeliucc $
 * @version $Id: ServerModelUtil.java 5 2008-09-01 12:08:42Z mikeliucc $
 */
public final class ServerModelUtil {

	private static final String CRYPTO_KEY = "three little pigs";

	private ServerModelUtil() {}

	public static PocPayload toPayload(String data) {
		String encrypted = encrypt(data);
		PocPayload payload = new PocPayload();
		payload.setPayload(encrypted);
		return payload;
	}

	public static void toModel(PocPayload payload, BaseModel model) {
		String decrypted = decrypt(payload.getPayload());
		model.serialize(decrypted);
	}

	private static String encrypt(String decrypted) {
		return toString(Crypto.encrypt(toByteArray(decrypted),
		                               toByteArray(CRYPTO_KEY)));

	}

	private static String decrypt(String encrypted) {
		return toString(Crypto.decrypt(toByteArray(encrypted),
		                               toByteArray(CRYPTO_KEY)));
	}

	private static byte[] toByteArray(String text) {
		if (text == null || text.length() < 1) { return new byte[0]; }
		char[] charArray = text.toCharArray();
		byte[] byteArray = new byte[charArray.length * 2];
		for (int i = 0; i < charArray.length; i++) {
			char c = charArray[i];
			byteArray[i * 2] = (byte) (c >>> 8);
			byteArray[(i * 2) + 1] = (byte) (c);
		}
		return byteArray;
	}

	private static String toString(byte[] array) {
		if (array == null || array.length < 1) { return ""; }
		char[] chars = new char[array.length / 2];
		for (int i = 0; i < chars.length; i++) {
			chars[i] = (char) (((char) array[i * 2] << 8) +
			                   ((byte) array[(i * 2) + 1] & 0xff));
		}

		return new String(chars);
	}


}
